<template>
  <div class="container mx-auto px-4 py-8">
    <div class="max-w-6xl mx-auto space-y-8">
      <!-- 操作说明组件 -->
      <InstructionsCard 
        :instructions="instructions" 
        :image-base-url="'/src/assets'" 
      />

      <!-- 参数配置卡片 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center mb-6">
          <div class="p-2 bg-blue-50 rounded-lg">
            <Settings class="h-6 w-6 text-blue-500" />
          </div>
          <h2 class="text-xl font-semibold text-gray-800 ml-3">
            单档模块配置
          </h2>
        </div>
        
        <ConfigurableForm
          v-model="localFormData"
          :config="formConfig"
          @update:modelValue="updateFormData"
        />
      </div>

      <!-- 字段信息卡片 -->
      <div class="bg-white rounded-xl shadow-sm p-6">
        <div class="flex items-center justify-between mb-6">
          <div class="flex items-center">
            <div class="p-2 bg-blue-50 rounded-lg">
              <Table class="h-6 w-6 text-blue-500" />
            </div>
            <h2 class="text-xl font-semibold text-gray-800 ml-3">字段信息</h2>
          </div>
        </div>

        <!-- 表格配置 -->
        <div class="border rounded-lg p-4 mb-4">
          <div class="flex items-center gap-4 flex-wrap">
            <!-- 表格名称 -->
            <div class="flex items-center gap-2">
              <span class="text-sm font-medium text-gray-600">表名:</span>
              <input 
                v-model="tableConfig.name"
                type="text"
                placeholder="输入表格名称"
                class="px-2 py-1 border rounded-md text-sm w-28"
              >
            </div>

            <!-- 表格类型名称 -->
            <div class="flex items-center gap-2">
              <span class="text-sm text-gray-600">定义类型:</span>
              <input 
                v-model="tableConfig.tableName"
                type="text"
                placeholder="type_master"
                class="px-2 py-1 border rounded-md text-sm w-32"
              >
            </div>

            <!-- 数组定义名称 -->
            <div class="flex items-center gap-2">
              <span class="text-sm text-gray-600">定义数组:</span>
              <input 
                v-model="tableConfig.arrayName"
                type="text"
                placeholder="g_master"
                class="px-2 py-1 border rounded-md text-sm w-32"
              >
            </div>

            <!-- 插入表名输入框 -->
            <div class="flex items-center gap-2">
              <span class="text-sm text-gray-600">插入表:</span>
              <input 
                v-model="tableConfig.insertTable"
                type="text"
                placeholder="输入插入表名"
                class="px-2 py-1 border rounded-md text-sm w-32"
              >
            </div>
          </div>
        </div>

        <!-- 字段配置表格 -->
        <TableDetails
          :data="tableData"
          :columns="tableColumns"
          :title="`${tableConfig.name || '表格'}字段配置`"
          @update:data="updateTableData"
        />
      </div>

      <!-- 生成代码按钮 -->
      <div class="flex justify-center">
        <button 
          @click="generateCode"
          class="inline-flex items-center px-6 py-2 text-sm font-medium text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors duration-200"
        >
          <Code class="h-5 w-5 mr-2" />
          生成代码
        </button>
      </div>

      <!-- 生成的代码预览 -->
      <GeneratedCode 
        v-if="isVisible && generatedCode" 
        :code-content="generatedCode" 
        :is-visible="isVisible"
        @copy-success="handleCopySuccess"
        @copy-error="handleCopyError"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { Settings, Code, Table } from 'lucide-vue-next';
import { ElMessage } from 'element-plus';
import GeneratedCode from '@/components/common/GeneratedCode.vue';
import ConfigurableForm from '@/components/common/ConfigurableForm.vue';
import TableDetails from '@/components/common/TableDetails.vue';
import InstructionsCard from '@/components/common/InstructionsCard.vue';
import { singleDocConfig } from '@/config/formConfigs';
import { singleDocColumns } from '@/config/tableColumns';
import { useSingleDocCodeGeneration } from '@/composables/useSingleDocCodeGeneration';
import instructions from '@/assets/single-doc-instructions.md';

const formConfig = singleDocConfig;
const localFormData = reactive({
  programId: '',
  programPath: '',
  module: ''
});

// 监听 programId 的变化并更新其他字段
watch(() => localFormData.programId, (newProgramId) => {
  if (newProgramId) {
    // 提取模块名 (前三位字母)
    localFormData.module = newProgramId.slice(0, 3);
    
    // 构建程序路径
    // 例如: cpji109 -> cpj/42f/cpji109
    const module = newProgramId.slice(0, 3);
    const subDir = '42f'; // 这里可以根据实际需求设置或计算
    localFormData.programPath = `${module}/${subDir}/${newProgramId}`;
  }
});

const updateFormData = (newValue) => {
  // 只更新不在联动规则中的字段
  const { programId, programPath, module, ...otherFields } = newValue;
  if (programId !== localFormData.programId) {
    localFormData.programId = programId;
    // programPath 和 module 会通过 watch 自动更新
  }
  Object.assign(localFormData, otherFields);
};

const tableData = ref([]);
const isVisible = ref(false);
const generatedCode = ref('');
const tableColumns = singleDocColumns;

const { generateSingleDocCode } = useSingleDocCodeGeneration();

// 添加表格配置
const tableConfig = reactive({
  name: '主表',
  tableName: 'type_master',
  arrayName: 'g_master',
  insertTable: 'sfa_file'
});

const updateTableData = (newData) => {
  // 直接使用 Excel 数据
  tableData.value = newData;
};

const generateCode = () => {
  if (localFormData && tableData.value) {
    // 将表格配置信息也传递给代码生成函数
    generatedCode.value = generateSingleDocCode(localFormData, {
      ...tableConfig,
      data: tableData.value
    });
    isVisible.value = true;
  } else {
    ElMessage.warning('请先填写表单和表格数据');
  }
};

const handleCopySuccess = () => {
  ElMessage.success('代码已成功复制到剪贴板');
};

const handleCopyError = () => {
  ElMessage.error('复制失败，请手动复制代码');
};
</script>